<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button
            v-permission="'excel_import'"
            type="warning"
            size="small"
            @click="$router.push('/import/index?type=user')"
          >excel导入</el-button>
          <el-button
            v-permission="'excel_export'"
            type="danger"
            size="small"
            @click="handleDownload"
          >excel导出</el-button>
          <el-button
            v-permission="'p-em-add'"
            type="primary"
            size="small"
            @click="addEmp"
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" type="index" :index="indexMethod" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{ row }">
              <img
                v-errorImg="defaultImg"
                :src="row.staffPhoto || defaultImg"
                alt=""
                class="avatar"
              >
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <!-- formatter =>  table表格中处理数据的方法  -->
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            :formatter="formatter"
          />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <!-- 通过插槽拿到时间数据，传给方法 -->
            <template #default="{ row }">
              {{ formatterTime(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{ row }">
              <el-button
                v-permission="'p-em-look'"
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button
                v-permission="'assign_role'"
                type="text"
                size="small"
                @click="showRoleDialog(row.id)"
              >分配角色</el-button>
              <el-button
                v-permission="'del_emp'"
                type="text"
                size="small"
                @click="delEmp(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          :current-page="queryData.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="queryData.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>
    <!-- 新增弹框 -->
    <add-dialog ref="addDialog" @updata="initData" />
    <!-- 分配角色弹框 -->
    <assign-role
      ref="openDialog"
      :show-role-dialog.sync="showDialog"
      :user-id="userId"
    />
  </div>
</template>
<script>
import { getEmployeesListApi, delEmployeesApi } from '@/api/employees'
import constant from '@/constant/employees'
import dayjs from 'dayjs'
import AddDialog from './componments/add-dialog.vue'
import Employees from '@/constant/employees'
import DefaultImg from '@/assets/common/bigUserHeader.png'
import AssignRole from './componments/assign-role.vue'
// import { mapGetters } from 'vuex'
export default {
  name: 'Employees',
  components: {
    AddDialog,
    AssignRole
  },
  data() {
    return {
      // 数据初始化接收列表数据
      list: [],
      // 请求参数
      queryData: {
        page: 1,
        size: 10
      },
      // 列表总数
      total: null,
      // loading 展示
      loading: false,
      // 展示默认图片
      defaultImg: DefaultImg,
      // 控制分配角色弹框显示隐藏
      showDialog: false,
      // id
      userId: ''
    }
  },
  // computed: {
  //   ...mapGetters(['roles'])
  // },
  created() {
    this.initData()
  },
  methods: {
    // todo 处理按钮权限
    // hasPermission(role) {
    //   return this.roles.points.includes(role)
    // },
    // !处理入职时间数据z
    formatterTime(value) {
      return value ? dayjs(value).format('YYYY-MM-DD') : ''
    },
    // !处理聘用形式数据
    formatter(row, column, cellValue) {
      // 1.导入枚举数据
      const hireType = constant.hireType
      const res = hireType.find((item) => item.id === +cellValue)
      // 2.判断是否有符合条件
      return res ? res.value : '未知'
    },
    // 数据初始化
    async initData() {
      this.loading = true
      const res = await getEmployeesListApi(this.queryData)
      this.list = res.data.rows
      this.total = res.data.total
      this.loading = false
    },
    // 每页显示多少个
    handleSizeChange(val) {
      this.queryData.pagesize = val
      this.queryData.page = 1
      this.initData()
    },
    // 跳转到相应的页面
    handleCurrentChange(val) {
      // console.log(val)
      this.queryData.page = val
      this.initData()
    },
    // 处理序号
    indexMethod(index) {
      return (this.queryData.page - 1) * this.queryData.size + index + 1
    },
    // 删除
    async delEmp(id) {
      await this.$confirm('确认删除吗', '提示')
      try {
        await delEmployeesApi(id)
        // 处理删除边界
        if (this.list.length === 1 && this.queryData.page > 1) {
          this.queryData.page--
        }
        this.$message.success('删除成功')
        this.initData()
      } catch (error) {
        return console.log(error)
      }
    },
    // 新增员工
    addEmp() {
      this.$refs.addDialog.showDialog = true
    },
    // excel 导出
    async handleDownload() {
      // 请求所有的列表数据
      const res = await getEmployeesListApi({ page: 1, size: this.total })

      // 定义转换需要使用的数据
      const headersArr = [
        '姓名',
        '手机号',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      const headersRelations = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const result = this.formateData(
        res.data.rows,
        headersArr,
        headersRelations
      )
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: headersArr,
          data: result,
          filename: '员工信息',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    // 处理表格数据
    formateData(data, headersArr, headersRelations) {
      const newArr = []
      data.forEach((item) => {
        const arr = []
        // 中文转成英文
        headersArr.forEach((val) => {
          // item[headersRelations[val]] 遍历数组的对象key值
          let value = item[headersRelations[val]]
          // 处理数据
          // headersRelations[val] 拿到 英文的key
          if (headersRelations[val] === 'formOfEmployment') {
            const hireType = Employees.hireType
            const obj = hireType.find((item) => item.id === +value)
            value = obj ? obj.value : '未知'
          }
          if (
            ['timeOfEntry', 'correctionTime'].includes(headersRelations[val])
          ) {
            value = this.formatterTime(value)
          }
          arr.push(value)
        })
        newArr.push(arr)
      })
      return newArr
    },
    // 分配角色显示隐藏
    showRoleDialog(id) {
      this.showDialog = true
      this.userId = id
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
}
</style>
